import 'package:boss/main.dart';
import 'package:boss/models/bill_summary.dart';
import 'package:boss/ui/widget/calendar/util/date_util.dart';
import 'package:boss/ui/widget/loading/loading.dart';
import 'package:flutter/material.dart';
import 'package:async/async.dart';
import 'package:flustars/flustars.dart' as flustars;
import 'package:hi_common/hi_common.dart';

class BillSummaryProvider extends ChangeNotifier {
  DateTime startDateTime;

  String get startDateTimeText {
    return startDateTime == null ? null : flustars.DateUtil.formatDate(startDateTime, format: flustars.DateFormats.full);
  }

  DateTime endDateTime;

  String get endDateTimeText {
    return endDateTime == null ? null : flustars.DateUtil.formatDate(endDateTime, format: flustars.DateFormats.full);
  }

  BillSummary billSummary;

  BillSummaryProvider() {
    startDateTime = DateUtils.startOfTheDay(DateTime.now());
    endDateTime = DateUtils.endOfTheDay(DateTime.now());
  }

  setEndDateTime(List<DateTime> dateTime) {
    startDateTime = dateTime[0];
    endDateTime = dateTime[1];
    notifyListeners();

    dateRangeChangeHandle();
  }

  dateRangeChangeHandle() async {
    if (startDateTime != null && endDateTime != null) {
      showLoadingToast();
      await queryBillSummary();
      hideLoadingToast();
    }
  }

  Future<Result<BillSummary>> queryBillSummary() async {
    try {
      var response = await api.orderPropInfo(
        startDate: startDateTimeText,
        endDate: endDateTimeText,
      );
      if (response.code != HttpRespCode.OK) {
        return Result.error(response.msg);
      }

      billSummary = response.data;
      notifyListeners();

      return Result.value(response.data);
    } catch (e) {
      return Result.error(e.toString());
    }
  }
}
